<?php

declare (strict_types=1);

namespace app\common\model\sharp;

use cores\BaseModel;
use cores\exception\BaseException;
use app\common\library\helper;
use app\common\service\Goods as GoodsService;
use think\model\relation\BelongsTo;

/**
 * 整点秒杀-秒杀商品sku模型
 * Class Goods
 * @package app\common\model\sharp
 */
class GoodsSku extends BaseModel
{
    // 定义表名
    protected $name = 'sharp_goods_sku';

    // 定义主键
    protected $pk = 'id';

    /**
     * 关联模型：主商品
     * @return BelongsTo
     */
    public function goods(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\sharp\\Goods", 'goods_id');
    }

    /**
     * 获取器：规格值ID集
     * @param $value
     * @return array|mixed
     */
    public function getSpecValueIdsAttr($value)
    {
        return helper::jsonDecode($value);
    }

    /**
     * 获取器：规格属性
     * @param $value
     * @return array|mixed
     */
    public function getGoodsPropsAttr($value)
    {
        return helper::jsonDecode($value);
    }

    /**
     * 设置器：规格值ID集
     * @param $value
     * @return false|string
     */
    public function setSpecValueIdsAttr($value)
    {
        return helper::jsonEncode($value);
    }

    /**
     * 设置器：规格属性
     * @param $value
     * @return false|string
     */
    public function setGoodsPropsAttr($value)
    {
        return helper::jsonEncode($value);
    }

    /**
     * 获取sku信息详情
     * @param int $sharpGoodsId
     * @param string $goodsSkuId
     * @return static|array|null
     */
    public static function detail(int $sharpGoodsId, string $goodsSkuId)
    {
        return static::get(['sharp_goods_id' => $sharpGoodsId, 'goods_sku_id' => $goodsSkuId]);
    }

    /**
     * 获取秒杀商品sku信息(指定的)
     * @param int $goodsId
     * @param int $sharpGoodsId
     * @param string $goodsSkuId
     * @return \app\common\model\GoodsSku|array|null
     * @throws BaseException
     */
    public static function getSkuInfo(int $goodsId, int $sharpGoodsId, string $goodsSkuId)
    {
        $goodsSkuInfo = GoodsService::getSkuInfo($goodsId, $goodsSkuId);
        $sharpSkuInfo = static::detail($sharpGoodsId, $goodsSkuId);
        if (empty($goodsSkuInfo) || empty($sharpSkuInfo)) {
            throwError('未找到SKU信息');
        }
        $goodsSkuInfo['original_price'] = $goodsSkuInfo['goods_price'];
        $goodsSkuInfo['seckill_price'] = $sharpSkuInfo['seckill_price'];
        $goodsSkuInfo['seckill_stock'] = $sharpSkuInfo['seckill_stock'];
        return $goodsSkuInfo;
    }
}